package com.iqilu.ksd.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.ADActivity;
import com.iqilu.ksd.activity.GalleryActivity;
import com.iqilu.ksd.activity.LiveActivity;
import com.iqilu.ksd.activity.MainActivity;
import com.iqilu.ksd.activity.MyActivity;
import com.iqilu.ksd.activity.NewsDetailActivity;
import com.iqilu.ksd.activity.PaikeActivity;
import com.iqilu.ksd.adapter.CommonAdapter;
import com.iqilu.ksd.bean.BannerBean;
import com.iqilu.ksd.bean.NewsItemBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.NewsType;
import com.iqilu.ksd.constant.UserInfo;
import com.iqilu.ksd.utils.ArrayUtils;
import com.iqilu.ksd.utils.BoxUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2016/11/18.
 */

public class CommonFragment extends BaseFragment {

    private int page;
    private ArrayList<NewsItemBean> list;
    private ArrayList<BannerBean> bannerList;
    private int catId;
    private String title;

    private CommonAdapter adapter;
    private RelativeLayout layEmpty;
    private ImageView btReload;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private RelativeLayout layLoading;
    private ImageView btLeft;
    private ImageView btRight;
    private TextView tvTitle;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_common, null);
        btLeft = getView(view, R.id.bt_left);
        btRight = getView(view, R.id.bt_right);
        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity) getActivity()).openDrawer();
            }
        });
        btRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, MyActivity.class));
            }
        });
        layEmpty = getView(view,R.id.lay_empty);
        btReload = getView(view,R.id.bt_reload);
        tvTitle = getView(view, R.id.tv_title);
        xRefreshView = getView(view, R.id.xRefreshView);
        rvList = getView(view, R.id.rv_list);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
        rvList.setHasFixedSize(true);
        layLoading = getView(view, R.id.lay_loading);
        layLoading.setVisibility(View.VISIBLE);

        btReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page = 1;
                layLoading.setVisibility(View.VISIBLE);
                xRefreshView.setVisibility(View.VISIBLE);
                getHead();
            }
        });

        adapter = new CommonAdapter(context);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(context));
        adapter.setOnItemClickListener(onItemClickListener);

        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getHead();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });
        rvList.setAdapter(adapter);

        Bundle bundle = getArguments();
        catId = bundle.getInt("catId");
        title = bundle.getString("title");
        tvTitle.setText("" + title);
        setZHTypeface(tvTitle);
        page = 1;
        getHead();
        return view;
    }

    private void getHead() {
        String url = Api.URL_SLIDE + "?catid=" + catId;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                bannerList = null;
                list = new ArrayList<NewsItemBean>();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                getList();
            }

            @Override
            public void onResponse(String response, int id) {
                bannerList = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<BannerBean>>() {
                });
                if (bannerList != null && bannerList.size() > 0) {
                    NewsItemBean bean = new NewsItemBean();
                    bean.setTitle(bannerList.get(0).getTitle());
                    bean.setThumb(bannerList.get(0).getImg());
                    bean.setRealtype(bannerList.get(0).getType());
                    if(bannerList.get(0).getType().equals(NewsType.URL) || bannerList.get(0).getType().equals(NewsType.AD)){
                        bean.setUrl(bannerList.get(0).getCon());
                    }else {
                        bean.setId(Integer.valueOf(bannerList.get(0).getCon()));
                    }
                    bean.setType(NewsType.HEAD);
                    list.add(bean);
                }
                getList();
            }
        });
    }

    private void getList() {
        String url = Api.URL_ARTICLE_LIST + "?page=" + page + "&catid=" + catId;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                afterRequest();
                if (page == 1) {
                    setEmpty();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                afterRequest();
                ArrayList<NewsItemBean> result = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<NewsItemBean>>() {
                });
                if (page == 1) {
                    if (result == null || result.size() == 0) {
                        setEmpty();
                        return;
                    }
                } else {
                    result = ArrayUtils.removeSame(list, result);
                    if (result == null || result.size() == 0) {
                        Toast.makeText(context, R.string.list_not_have, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (list == null) {
                        return;
                    }
                }
                list.addAll(result);
                adapter.setData(list);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void afterRequest() {
        layLoading.setVisibility(View.GONE);
        layEmpty.setVisibility(View.GONE);
        if (page == 1) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }
    }

    private void setEmpty() {
        adapter.setData(null);
        adapter.notifyDataSetChanged();
        layEmpty.setVisibility(View.VISIBLE);
        xRefreshView.setVisibility(View.GONE);
    }

    private CommonAdapter.OnItemClickListener onItemClickListener = new CommonAdapter.OnItemClickListener() {
        @Override
        public void OnItemClickListener(View view, int position) {
            String type;
            Intent intent = null;
            NewsItemBean item = list.get(position);
            if(item.getType().equals(NewsType.HEAD)){
                type = item.getRealtype();
            }else {
                type = item.getType();
            }

            if (type.equals(NewsType.ARTICLE)) {
                intent = new Intent(context, NewsDetailActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("catId", item.getCatid());
            } else if (type.equals(NewsType.GALLERY) || type.equals(NewsType.PHOTO)) {
                intent = new Intent(context, GalleryActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("catId", item.getCatid());
                intent.putExtra("position", 0);
            } else if (type.equals(NewsType.AD) || type.equals(NewsType.URL)) {
                intent = new Intent(context, ADActivity.class);
                intent.putExtra("title", item.getTitle());
                intent.putExtra("type", type);
                intent.putExtra("adUrl", item.getUrl());
                if (type.equals(NewsType.AD)) {
                    intent.putExtra("shareicon", item.getShareicon());
                } else {
                    intent.putExtra("thumb", item.getThumb());
                }
            } else if (type.equals(NewsType.LIVE)) {
                intent = new Intent(context, LiveActivity.class);
                intent.putExtra("id", item.getId());
            } else if (type.equals(NewsType.CLUE)) {
                intent = new Intent(context, PaikeActivity.class);
                intent.putExtra("id", item.getId());
            }
            if (intent != null) {
                startActivity(intent);
            }
        }
    };
}
